package com.guan.serviceUcenter.controller;

import com.google.gson.Gson;
import com.guan.commonutils.JwtUtils;
import com.guan.serviceUcenter.entity.UcenterMember;
import com.guan.serviceUcenter.service.UcenterMemberService;
import com.guan.serviceUcenter.utils.ConstantWxUtil;
import com.guan.serviceUcenter.utils.HttpClientUtils;
import com.guan.servicebase.exceptonhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * @Date: 2023/4/20 10:16
 * @Author: 管奇安
 * @Description:
 */
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    //扫码后请求地址 获取扫描信息
    @GetMapping("callback")
    public String callback(String code,String state){
        System.out.println("code = "+code+" , state = "+state);
        try{
            //使用code请求微信固定的地址 得到access_token openid
            //向认证服务器发送请求换取access_token
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    ConstantWxUtil.WX_OPEN_APP_ID,
                    ConstantWxUtil.WX_OPEN_APP_SECRET,
                    code);

            //请求拼接后的地址
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo = "+accessTokenInfo);

            //解析json字符串
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String accessToken = (String)map.get("access_token");
            String openid = (String)map.get("openid");

            //查询数据库当前用用户是否曾经使用过微信登录
            UcenterMember member = ucenterMemberService.getByOpenid(openid);
            if(member == null){
                System.out.println("新用户注册");
                //访问微信的资源服务器，获取用户信息 固定地址
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
                String resultUserInfo = null;
                try {
                    resultUserInfo = HttpClientUtils.get(userInfoUrl);
                    System.out.println("resultUserInfo==========" + resultUserInfo);
                } catch (Exception e) {
                    throw new GuliException(20001, "获取用户信息失败");
                }
                //解析json
                HashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo, HashMap.class);
                String nickname = (String)mapUserInfo.get("nickname");
                String headimgurl = (String)mapUserInfo.get("headimgurl");
                //向数据库中插入一条记录
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                ucenterMemberService.save(member);
            }
            //登录
            //使用jwt根据member信息生成token
            String jwtToken = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+jwtToken;

        }catch (Exception e) {
            throw new RuntimeException(e);
        }

    }



    //生成微信扫描的二维码
    @GetMapping("login")
    public String getWxCode() throws UnsupportedEncodingException {
        // 微信开放平台授权baseUrl    s% 代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirect_url = ConstantWxUtil.WX_OPEN_REDIRECT_URL;
        String encode = URLEncoder.encode(redirect_url, "utf-8");

        String url = String.format(
                            baseUrl,
                            ConstantWxUtil.WX_OPEN_APP_ID,
                            encode,
                            "atguigu"
                    );

        //重定向
        return "redirect:"+url;
    }



}
